//
//  XDInfoViewController.m
//  XDHoHo
//
//  Created by xie yajie on 13-11-12.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "XDInfoViewController.h"

#import <ShareSDK/ShareSDK.h>
#import "XDSegmentedView.h"
#import "XDActivityModel.h"
#import "XDActivityView.h"
#import "XDInfoDetailViewController.h"

@interface XDInfoViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, XDActivityViewDelegate>
{
    NSMutableArray *_dataSource;
}

@property (strong, nonatomic) UIView *topView;
@property (strong, nonatomic) UITableView *tableView;

@end

@implementation XDInfoViewController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        _dataSource = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
    
    [self requestDataForRefresh:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

#pragma mark - getting

- (UIView *)topView
{
    if (_topView == nil) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        _topView.backgroundColor = [UIColor blackColor];
        
        NSArray *array = [[NSArray alloc] initWithObjects: @"最新", @"热门", @"精华", nil];
        XDSegmentedView *segmentedView = [[XDSegmentedView alloc] initWithFrame:CGRectMake(0, 0, 60 * array.count, _topView.frame.size.height)];
        segmentedView.buttonTitleDataSource = array;
        segmentedView.buttonTitleSelectedColor = [UIColor whiteColor];
//        segmentedView.backgroundImgName = @"segmented_menu_bg.png";
        segmentedView.moveImgName = @"segmented_menu_line.png";
        segmentedView.style = XDSegmentedViewStyleBottomMove;
        [segmentedView addTarget:self action:@selector(segmentedControlChangedValue:)];
        [segmentedView createSubButton];
        [_topView addSubview:segmentedView];
        
        UIButton *refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(_topView.frame.size.width - 60, (_topView.frame.size.height - 30) / 2, 50, 30)];
        [refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
        [refreshButton setImage:[UIImage imageNamed:@"refresh_highlighted.png"] forState:UIControlStateHighlighted];
        [refreshButton setBackgroundImage:[[UIImage imageNamed:@"info_button_bg_hl.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5] forState:UIControlStateNormal];
        [refreshButton addTarget:self action:@selector(refreshAction:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:refreshButton];
    }
    
    return _topView;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.topView.frame.origin.y + self.topView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - (self.topView.frame.origin.y + self.topView.frame.size.height) - 44) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:240 / 255.0 blue:235 / 255.0 alpha:1.0];
    }
    
    return _tableView;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
    }
    else{
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
    }
    
    XDActivityModel *model = [self activityModelAtIndexPath:indexPath];
    XDActivityView *activityView = [[XDActivityView alloc] initWithFrame:CGRectMake(10.0, 10.0, tableView.frame.size.width - 20, 0.0) activity:model];
    activityView.delegate = self;
    activityView.otherInfo = @{@"indexPath": indexPath};
    [activityView setupActivityView];
    [cell.contentView addSubview:activityView];
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XDActivityModel *model = [self activityModelAtIndexPath:indexPath];
    
    if (model) {
        XDActivityView *activityView = [[XDActivityView alloc] initWithFrame:CGRectMake(10.0, 10.0, tableView.frame.size.width - 20, 0.0) activity:model];
        return [activityView activityViewHeight] + 10;
    }
    
    return 44.0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    // ...
    // Pass the selected object to the new view controller.
    XDInfoDetailViewController *detailVIewController = [[XDInfoDetailViewController alloc] initWithActivityModel:[_dataSource objectAtIndex:indexPath.row]];
    [self.tabBarController.navigationController pushViewController:detailVIewController animated:YES];
}

#pragma mark - XDActivityViewDelegate

//点击分享按钮
- (void)contactActivityViewShareButtonClicked:(XDActivityView *)activityView
{
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"这是一条测试信息"
                                       defaultContent:@""
                                                image:nil/*[ShareSDK imageWithPath:imagePath]*/
                                                title:@"ShareSDK"
                                                  url:@"http://www.sharesdk.cn"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    ///////////////////////
    //以下信息为特定平台需要定义分享内容，如果不需要可省略下面的添加方法
    
    //定制人人网信息
    [publishContent addRenRenUnitWithName:@"Hello 人人网"
                              description:INHERIT_VALUE
                                      url:INHERIT_VALUE
                                  message:INHERIT_VALUE
                                    image:INHERIT_VALUE
                                  caption:nil];
    
    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    
    id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:@"内容分享"
                                                              oneKeyShareList:[NSArray defaultOneKeyShareList]
                                                               qqButtonHidden:YES
                                                        wxSessionButtonHidden:YES
                                                       wxTimelineButtonHidden:YES
                                                         showKeyboardOnAppear:NO
                                                            shareViewDelegate:nil
                                                          friendsViewDelegate:nil
                                                        picViewerViewDelegate:nil];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:shareOptions
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]);
                                }
                            }];
}

//点击赞按钮
- (void)contactActivityViewPraiseButtonClicked:(XDActivityView *)activityView
{
    
}

//点击踩按钮
- (void)contactActivityViewTrampleButtonClicked:(XDActivityView *)activityView
{
    
}

//点击收藏按钮
- (void)contactActivityViewFavoriteButtonClicked:(XDActivityView *)activityView
{
    //判断是否登录
    //????
    
    //如果未登录
    UIAlertView *logoutAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功！登录后收藏的内容永久保存，换手机也照样找回来" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:@"现在登录", nil];
    [logoutAlertView show];
    
    //如果登录了
//    UIAlertView *loginAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功！收藏的内容永久保存，换手机也照样找回来" nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        //
    }
}

#pragma mark - XDSegmentedControl methods

- (void)segmentedControlChangedValue:(XDSegmentedView *)segmentedControl
{
    if (segmentedControl.selectedIndex == 0) {
        
    }
    else{
        
    }
}

#pragma mark - data

- (XDActivityModel *)activityModelAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath) return nil;
    
    if (indexPath.row < [_dataSource count]) {
        return [_dataSource objectAtIndex:indexPath.row];
    }
    
    return nil;
}

- (void)requestDataForRefresh:(BOOL)isRefresh
{
    if (isRefresh) {
        [_dataSource removeAllObjects];
    }
    else{
        
    }
    
    //测试数据
    
    //附件图片
    NSMutableDictionary *appendix1 = [NSMutableDictionary dictionary];
    NSDictionary *image1 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", KMODEL_ID, @"1", KMODEL_ACCOUNTID, @"1.png", KMODEL_NAME, @"1.png", KAPPENDIX_SOURCEPATH, nil];
    NSDictionary *image2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2", KMODEL_ID, @"2", KMODEL_ACCOUNTID, @"2.png", KMODEL_NAME, @"2.png", KAPPENDIX_SOURCEPATH, nil];
    NSArray *images = [NSArray arrayWithObjects:image1, image2, nil];
    [appendix1 setObject:images forKey:KAPPENDIX_IMAGE];
    
    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", KMODEL_ID, @"1", KMODEL_ACCOUNTID, @"xieyajie", KMODEL_NAME, @"", KMODEL_HEADPATH, [NSDate date], KMODEL_CREATEDATE, @"北京市海淀区海淀西大街48号图书城步行街内鑫鼎宾馆北京市海淀区海淀西大街48号图书城步行街内鑫鼎宾馆", KMODEL_CONTENT, appendix1, KAPPENDIX, @"10", KACTIVITY_COUNT_COMMENT, @"0", KACTIVITY_COUNT_PRAISE, @"0", KACTIVITY_COUNT_TRAMPLE, @"0", KACTIVITY_COUNT_FAVORITE, nil];
    XDActivityModel *activityModel1 = [[XDActivityModel alloc] initWithDictionary:dic1];
    [_dataSource addObject:activityModel1];
    
    //附件音频
    NSMutableDictionary *appendix2 = [NSMutableDictionary dictionary];
    NSDictionary *audio1 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", KMODEL_ID, @"1", KMODEL_ACCOUNTID, @"1.png", KMODEL_NAME, @"1.png", KAPPENDIX_SOURCEPATH, @"10", KAPPENDIX_DURATION, nil];
    NSDictionary *audio2 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", KMODEL_ID, @"1", KMODEL_ACCOUNTID, @"1.png", KMODEL_NAME, @"1.png", KAPPENDIX_SOURCEPATH, @"10", KAPPENDIX_DURATION, nil];
    NSArray *videos = [NSArray arrayWithObjects:audio1, audio2, nil];
    [appendix2 setObject:videos forKey:KAPPENDIX_AUDIO];
    
    NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", KMODEL_ID, @"1", KMODEL_ACCOUNTID, @"xieyajie", KMODEL_NAME, @"", KMODEL_HEADPATH, [NSDate date], KMODEL_CREATEDATE, @"北京市海淀区海淀西大街48号图书城步行街内鑫鼎宾馆", KMODEL_CONTENT, appendix2, KAPPENDIX, @"10", KACTIVITY_COUNT_COMMENT, @"0", KACTIVITY_COUNT_PRAISE, @"0", KACTIVITY_COUNT_TRAMPLE, @"0", KACTIVITY_COUNT_FAVORITE, nil];
    XDActivityModel *activityModel2 = [[XDActivityModel alloc] initWithDictionary:dic2];
    [_dataSource addObject:activityModel2];
}

#pragma mark - button action

- (void)refreshAction:(id)sender
{
    
}


@end
